﻿using Microsoft.Extensions.Caching.Memory;

namespace MyFurion.Unility.Generic
{
    /// <summary>
    /// Memory缓存
    /// </summary>
    public class MemoryCache:ITransient
    {
        private readonly IMemoryCache _cache;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cache"></param>
        public MemoryCache(IMemoryCache cache)
        {
            _cache = cache;
        }

        /// <summary>
        /// 设置缓存(秒)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="time">过期时间 单位秒</param>
        public void SetCache(string key, string value, int time)
        {
            _cache.Set(key, value, new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(time)));
        }
        /// <summary>
        /// 设置缓存(分钟)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="time">过期时间 单位分钟</param>
        public void SetCacheMin(string key, string value, int time)
        {
            _cache.Set(key, value, new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(time)));
        }
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetCache(string key)
        {
            var value = _cache.Get(key);
            return value != null ? value.ToString() : "";
        }
        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key"></param>
        public void DelCache(string key)
        {
            _cache.Remove(key);
        }
    }
}
